import express from 'express'
import axios from 'axios'
import qs from 'qs'

var http = require('http') // express带的http模块， 无需安装
var url = require('url') // 把接收到的url转换为url对象， http://baidu.com -> {}， 无需安装
var querystring = require('querystring')

import {REMOTE_ADDRESS, isPcEnable, token} from '../config'
// const {REMOTE_ADDRESS, isPcEnable, token} = require('../config')

// Create express router
const router = express.Router()

// Transform req & res to have the same API as express
// So we can use res.status() & res.json()
const app = express()
router.use((req, res, next) => {
  Object.setPrototypeOf(req, app.request)
  Object.setPrototypeOf(res, app.response)
  req.res = res
  res.req = req
  next()
})

// Add POST - /dispatch
router.post('*', (req, res) => {
  console.log('dispatch')
  const accessToken = isPcEnable ? token : (req.session.accessToken || '')

  let { method, url, data:json, contentType } = req.body

  // var nodeAjax = new NodeAjax()

  const CONTENT_TYPE = {
    FORM_DATA: 'multipart/form-data; charset=UTF-8',
    FORM: 'application/x-www-form-urlencoded; charset=UTF-8',
    JSON: 'application/json; charset=UTF-8'
  }
  console.log('accessToken:', accessToken)
  if (method === 'POST') {
    const config = {
      method,
      baseURL: REMOTE_ADDRESS,
      url,
      data: contentType === 'JSON' ? JSON.stringify(json) : qs.stringify(json),
      headers: {
        'Content-Type': CONTENT_TYPE[contentType || 'FORM'],
        Authorization: accessToken
      }
    }
    const message = { url, accessToken, json }
    const AXIOS_DELAY = 1000
    let timer = () => {}
    
    axios(config).then(resp => { sendResponse(res, resp, message) }).catch(() => {
      timer = setTimeout(() => {
        clearTimeout(timer)
        axios(config).then(resp => { sendResponse(res, resp, message) }).catch(() => {
          timer = setTimeout(() => {
            clearTimeout(timer)
            axios(config).then(resp => { sendResponse(res, resp, message) }).catch(() => {
              res.status(501).json({ message: 'Bad credentials' })
              res.end()
            })
          }, AXIOS_DELAY);
        })
      }, AXIOS_DELAY)
    })

    // nodeAjax.post(REMOTE_ADDRESS + url, json, accessToken, function (resp) {
    //   console.log(url, '| token:', accessToken, '| data:', json)

    //   res.send(resp)
    //   res.end()
    // }, contentType || 'FORM')
  }
  // res.json({ username: 'demo' })
  // res.status(401).json({ message: 'Bad credentials' })
})
function sendResponse(res, resp, {url, accessToken, json}) {
  console.log(url, '| token:', accessToken, '| data:', json)
  res.send(resp.data)
  res.end()
}



function NodeAjax() {
  const CONTENT_TYPE = {
    FORM_DATA: 'multipart/form-data; charset=UTF-8',
    FORM: 'application/x-www-form-urlencoded; charset=UTF-8',
    JSON: 'application/json; charset=UTF-8'
  }
  // or NodeAjax.prototype.post = function(){}
  this.post = function (path, data, token, callback, contentType = 'FORM') {
    var urlObj = url.parse(path)
    var contents
    var headers = { 'content-type': CONTENT_TYPE[contentType] }
    if (contentType === 'JSON') {
      contents = JSON.stringify(data)
    } else {
      contents = querystring.stringify(data)
      Object.assign(headers, {'Content-Length': contents.length, Authorization: token})
    }
    var option = {
      method: 'POST',
      hostname: urlObj.hostname,
      port: urlObj.port,
      path: urlObj.path,
      headers: headers
    }

    var httpCallback = function (response) {
      var body = ''
      response.on('data', function (data) {
        body += data
      })
      response.on('end', function () {
        callback(body)
      })
    }
    var res = http.request(option, httpCallback)
    res.write(contents) // 发送内容
    res.end()
  }

  this.get = function (path, callback) {
    var urlObj = url.parse(path)
    var option = {
      method: 'GET',
      hostname: urlObj.hostname,
      port: urlObj.port,
      path: urlObj.path,
      headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', Authorization: token }
    }
    var httpCallback = function (response) {
      var body = ''
      response.on('data', function (data) {
        body += data
      })
      response.on('end', function () {
        callback(body)
      })
    }
    var req = http.request(option, httpCallback)
    req.end()
  }
}

// Export the server middleware
export default {
  path: '/dispatch',
  handler: router
}
